﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Moon.Sql
{
    internal class BinarExpressionProvider
    {
        private ExpressionProvide _expression = null;

        public BinarExpressionProvider(ExpressionProvide expression)
        {
            _expression = expression;
        }

        /// <summary>
        /// 解析条件表达式 where(i=>true)
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public string Resolve(Expression exp)
        {
            BinaryExpression be = exp as BinaryExpression;
            ExpressionType type = be.NodeType;
            StringBuilder leftSql = new StringBuilder("(");
            leftSql.Append(_expression.Resolve(be.Left));
            string rightSql = _expression.Resolve(be.Right);
            leftSql.Append(_expression.ExpressionTypeCast(type));
            if (rightSql == "null")
            {
                if (leftSql.ToString().EndsWith(" = "))
                {
                    string s = leftSql.ToString(0, leftSql.Length - 2);
                    leftSql.Clear().Append(s).Append("is null");
                }
                else if (leftSql.ToString().EndsWith(" <> "))
                {
                    string s = leftSql.ToString(0, leftSql.Length - 3);
                    leftSql.Clear().Append(s).Append("is not null");
                }
            }
            else
            {
                leftSql.Append(rightSql);
            }
            leftSql.Append(")");
            return leftSql.ToString();
        }
    }
}
